package com.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * TODO
 *
 * @Description
 * @Author tm
 * @Date 2022-12-20 21:29
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class WxTemplateMessageService {
    private  final WxMpService wxMpService;

    public String sendMessage(String openId, String url, String templateId, List<WxMpTemplateData> dataList){
        // 发送模板消息接口
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                // 接收者openid
                .toUser(openId)
                // 模板id
                .templateId(templateId)
                // 模板跳转链接
                .url(url)
                .build();
        // 添加模板数据
        for(WxMpTemplateData data :dataList){
            templateMessage.addData(data);
        }
//        templateMessage.addData(new WxMpTemplateData("first", "标题"))
//                .addData(new WxMpTemplateData("keyword1", "1"))
//                .addData(new WxMpTemplateData("keyword2", "2"))
//                .addData(new WxMpTemplateData("keyword3", "3"))
//                .addData(new WxMpTemplateData("keyword4", "4"))
//                .addData(new WxMpTemplateData("keyword5", "5"))
//                .addData(new WxMpTemplateData("remark", "1111111"));
        String msgId = null;
        try {
            // 发送模板消息
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            System.out.println("msgId :" + msgId);
        } catch (WxErrorException e) {
            e.printStackTrace();
        } finally {

        }
        return msgId;
    }
}
